package com.xw.floatlib;

import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;

import com.xw.floatlib.callback.FloatCallBack;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class FloatActionController {

    private FloatCallBack mFloatCallBack;
    public boolean isStartService = false;

    public FloatActionController() {
    }


    public static class FloatActionProviderHolder{
        private static final FloatActionController instance = new FloatActionController();
    }
    public static FloatActionController getInstance(){
        return FloatActionProviderHolder.instance;
    }

    /**
     * 判断是否开启了悬浮窗权限
     * @param context
     * @return
     */
    public boolean openWindowPermission(Context context){
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
            return true;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            try {
                Class cls = Class.forName("android.content.Context");
                Field declaredField = cls.getDeclaredField("APP_OPS_SERVICE");
                declaredField.setAccessible(true);
                Object obj = declaredField.get(cls);
                if (!(obj instanceof String)) {
                    return false;
                }
                String str2 = (String) obj;
                obj = cls.getMethod("getSystemService", String.class).invoke(context, str2);
                cls = Class.forName("android.app.AppOpsManager");
                Field declaredField2 = cls.getDeclaredField("MODE_ALLOWED");
                declaredField2.setAccessible(true);
                Method checkOp = cls.getMethod("checkOp", Integer.TYPE, Integer.TYPE, String.class);
                int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUid(), context.getPackageName());
                return result == declaredField2.getInt(cls);
            } catch (Exception e) {
                return false;
            }
        } else {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
//                if (appOpsMgr == null)
//                    return false;
//                int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), context
//                        .getPackageName());
//                return mode == AppOpsManager.MODE_ALLOWED || mode == AppOpsManager.MODE_IGNORED;
//            } else {
                return Settings.canDrawOverlays(context);
//            }
        }
    }

    /**
     * 申请悬浮窗权限
     * @param context
     */
    public void requestDrawOverLays(Context context) {
        if (Build.VERSION.SDK_INT >= 23 && !Settings.canDrawOverlays(context)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        }
    }

    /**
     * 开启悬浮窗服务
     */
    public void startMonkServer(Context context,List<MusicData> musicDatas,int postion,String plate_id) {
        if (openWindowPermission(context)){
            Intent intent = new Intent(context, FloatMonkService.class);
            intent.putExtra("music_dates", (Serializable) musicDatas);
            intent.putExtra("start_index",postion);
            intent.putExtra("plate_id",plate_id);
            context.startService(intent);
            isStartService = true;
        }else{
            Toast.makeText(context, "请开启悬浮窗权限!", Toast.LENGTH_SHORT).show();
            requestDrawOverLays(context);
        }

    }

    /**
     * 关闭悬浮窗
     */
    public void stopMonkServer(Context context) {
        Intent intent = new Intent(context, FloatMonkService.class);
        context.stopService(intent);
        isStartService = false;
    }

    /**
     * 注册监听
     */
    public void registerCallLittleMonk(FloatCallBack callLittleMonk) {
        mFloatCallBack = callLittleMonk;
    }

    public void unRegisterCallbackMonk(){
        mFloatCallBack = null;
    }

    /**
     * 悬浮窗的显示
     * @param
     */
    public void show() {
        if (mFloatCallBack == null) return;
        mFloatCallBack.show();
    }

    /**
     * 悬浮窗的隐藏
     */
    public void hide() {
        if (mFloatCallBack == null) return;
        mFloatCallBack.hide();
    }

    /**
     * 移除
     */
    public void remove(){
        if (mFloatCallBack == null) return;
        mFloatCallBack.cancle();
    }

    /**
     * 更新进度条
     * @param progress
     */
    public void updataProgress(int progress){
        if (mFloatCallBack == null)return;
        mFloatCallBack.updataProgress(progress);
    }

    /**
     * 上一首
     */
    public void lastMusic(){
        if (mFloatCallBack == null)return;
        mFloatCallBack.last();
    }

    /**
     * 下一首
     */
    public void nextMusic(){
        if (mFloatCallBack == null)return;
        mFloatCallBack.next();
    }

    public void stop2Start(){
        if (mFloatCallBack == null)return;
        mFloatCallBack.stop2Start();
    }

    /**
     * 暂停/开始
     */
    public void cancle(){
        if (mFloatCallBack == null)return;
        mFloatCallBack.cancle();
    }

    /**
     * 播放传入的音频
     * @param
     */
    public void playItem(int position, List<MusicData> musicDataList,String plate_id){
        if (mFloatCallBack == null && !isStartService)return;
        mFloatCallBack.playItem(position, musicDataList,plate_id);
    }
}
